#!/usr/bin/python3
# coding: utf-8
# file: asyncio_.py
# 同一个线程中的异步读写, 称作协程
# 2018-06-21
import asyncio
import threading
from aiohttp import web

def asyncio_func_1():
	'初试单线程异步读写'
	@asyncio.coroutine
	def hello():
		print('Hello World (%s)' % threading.currentThread())
		yield from asyncio.sleep(1)
		print('Hello again (%s)' % threading.currentThread())

	async def hello2():
		print('Hello2 World (%s)' % threading.currentThread())
		await asyncio.sleep(1)
		print('Hello2 again (%s)' % threading.currentThread())

	async def wget(host):
		print('wget %s...' % host)
		connect = asyncio.open_connection(host, 80)
		reader, writer = await connect
		user_agent = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36'
		header = 'GET / HTTP/1.0\r\nHost: %s\r\nUser-Agent: %s\r\n\r\n' % (host, user_agent)
		writer.write(header.encode('utf-8'))
		await writer.drain()
		while True:
			line = await reader.readline()
			if line == b'\r\n':
				break
			print('%s header > %s' % (host, line.decode('utf-8').rstrip()))
		writer.close()

	loop = asyncio.get_event_loop()
	tasks = [hello(), hello(), hello2(), hello2()] + [wget(host) for host in ['www.sina.com.cn', 'www.sohu.com', 'www.163.com']]
	loop.run_until_complete(asyncio.wait(tasks))
	loop.close()

# asyncio_func_1()

def asyncio_func_2():
	'单线程异步web服务'
	async def index(request):
	    await asyncio.sleep(0.5)
	    return web.Response(body=b'<h1>Index</h1>', content_type='text/html')

	async def hello(request):
	    await asyncio.sleep(0.5)
	    text = '<h1>hello, %s!</h1>' % request.match_info['name']
	    return web.Response(body=text.encode('utf-8'), content_type='text/html')

	async def init(loop):
	    app = web.Application(loop=loop)
	    app.router.add_route('GET', '/', index)
	    app.router.add_route('GET', '/hello/{name}', hello)
	    srv = await loop.create_server(app.make_handler(), '127.0.0.1', 8000)
	    print('Server started at http://127.0.0.1:8000...')
	    return srv

	loop = asyncio.get_event_loop()
	loop.run_until_complete(init(loop))
	loop.run_forever()

asyncio_func_2()